package top.huxy.boot.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import top.huxy.boot.annotation.Master;
import top.huxy.boot.model.entity.Admin;
import top.huxy.boot.util.StringUtils;
import top.huxy.boot.util.obj.Result;
import top.huxy.boot.util.obj.ThreadLocalAdmin;

/**
 * @Classname MasterAspect
 * @Description 对持有Master注解的方法行权限校验, 权限不符合，无法操作
 * @Date 2021/10/18 17:01
 * @Created by huxy
 */
@Aspect
@Component
@Slf4j
public class MasterAspect {
    @Pointcut("@annotation(master)")
    public void timePointcut(Master master) {
    }

    @Around("timePointcut(master)")
    public Object around(ProceedingJoinPoint joinPoint, Master master) throws Throwable {
        Admin current = ThreadLocalAdmin.current();
        if (current == null) return Result.clientError("没有这个权限");

        Integer role = current.getRole();

        if (role == null) return Result.clientError("没权限操作");

        if (!master.value().hasAble(role)) {
            String msg = master.msg();
            if (StringUtils.isEmpty(msg)) {
                msg = master.value().msg();
            }
            return Result.clientError(msg);
        }

        return joinPoint.proceed();
    }
}
